<?php

class Html extends Widget
{
    private $htmlOptions=array(
        'elementId'=>'',
        'class'=>'link',
        'href'=>'',
        'dataId'=>'',
        'dataLink'=>'',
        'onClick'=>'',
        'linkName'=>'',
    );

    public function __construct($params=array())
    {
        $this->setParams($params);
    }

    public function link($route,$params=array())
    {
        if($params) $this->setParams($params);

        foreach($this->htmlOptions as $name=>$value){
            $$name=$value;
        }

        if(!$this->htmlOptions['linkName']) $linkName=isset($params['linkName']) ? $params['linkName'] : ($route ? str_replace('/','-',$route) : 'link');

        if(!$route) $route=$this->htmlOptions['href'];
        $href=Sys::app()->request->createUrl($route,$this->params);

        $view='<a href="'.$href.'"';
        if(isset($elementId) && $elementId) $view.=' id="'.$elementId.'"';
        if(isset($class) && $class) $view.=' class="'.$class.'"';
        if(isset($dataId) && $dataId) $view.=' data-id="'.$dataId.'"';
        if(isset($dataLink) && $dataLink) $view.=' data-link="'.$dataLink.'"';
        if(isset($onClick) && $onClick) $view.=' onclick="'.$onClick.'"';

        if(isset($linkName) && $linkName) $view.='>'.$linkName.'</a>';
        else $view.=' />';

        return $view;
    }

    public function addToUrl($url,$params=array())
    {
        if(!$params && is_array($url)){
            $params=$url;
            $url=Sys::app()->request->currentUrl;
        }

        $endPos=sizeof($url)-1;
        if($url[$endPos]=='/') $url=substr($url,0,$endPos);

        foreach($params as $name=>$value){
            $url.='/'.$name.'/'.$value;
        }
        return $url;
    }

    private function setParams($params=array())
    {
        if(isset($params['htmlOptions']) && is_array($params['htmlOptions'])){
            foreach(array_keys($this->htmlOptions) as $name){
                if(isset($params['htmlOptions'][$name])){
                    $this->htmlOptions[$name]=$params['htmlOptions'][$name];
                }
            }
            unset($params['htmlOptions']);
        }elseif(is_array($params)){
            foreach(array_keys($this->htmlOptions) as $name){
                if(isset($params[$name])){
                    $this->htmlOptions[$name]=$params[$name];
                    unset($params[$name]);
                }
            }
        }
        $this->params=$params;
    }
}